package com.android.aishangauction.activity.mine;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.aishangauction.R;
import com.android.aishangauction.activity.BaseObject;
import com.android.aishangauction.activity.MainTab;
import com.android.aishangauction.app.BaseActivity;
import com.android.aishangauction.model.group.BusinessVoucherListData;
import com.android.aishangauction.model.group.BusinessVoucherListDataCallback;
import com.android.aishangauction.utils.ConstantsUrl;
import com.android.aishangauction.utils.HttpUtils;
import com.android.aishangauction.utils.LoginState;
import com.android.aishangauction.utils.ObjectUtils;
import com.android.aishangauction.view.recycleview.CustomLoadMoreView;
import com.android.aishangauction.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/9/21.
 */

public class BuyTicketActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R.id.click_resetnetwork_refresh)
    TextView clickResetnetworkRefresh;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.main_top_title)
    TextView mainTopTitle;
    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.really_price)
    TextView really_price;
    @BindView(R.id.really_bean)
    TextView really_bean;
    @BindView(R.id.buy_number)
    TextView buy_number;

    private BuyTicketActivity mcontext;
    private boolean networkConnected;
    private LinearLayoutManager mLayoutManager =  new LinearLayoutManager(mcontext);
    private int page = 1;
    private ArrayList<BusinessVoucherListData.DataBean.ListBean> listdata ;
    private AdaptList adapter;
    private String currentid;
    private int currentcoin;
    private Double currentprice = 0.0;
    private int singlecoin;
    private Double singleprice = 0.0;
    private int currentnumber;
    private String  currenttitle ="";
    private String currentsummary="";
    private String currentthumb="";
    private String currentstime="";
    private String currentetime="";
    private boolean isInit = true;
    AlertDialog dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buyticket);
        ButterKnife.bind(this);
        mcontext = this;
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        RefreshData();
        GetDataListData(page);
    }
    private Message message;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    really_price.setText(currentprice+"");
                    really_bean.setText(currentcoin+"");
                    buy_number.setText(currentnumber+"");
                    break;
            }
        }
    };
    private void RefreshData() {
        adapter = new AdaptList(mcontext, null, "0");
        //  adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                isInit = false;
                currentid = adapter.getItem(position).getId();
                singlecoin= Integer.parseInt(adapter.getItem(position).getCoin());
                singleprice =  Double.parseDouble(adapter.getItem(position).getPrice());
                currentcoin = singlecoin;
                currentprice = singleprice;
                currentnumber = 1;
                currenttitle = adapter.getItem(position).getTitle();
                currentsummary = adapter.getItem(position).getSummary();
                currentthumb = adapter.getItem(position).getThumb();
                currentstime = adapter.getItem(position).getStart_time();
                currentetime = adapter.getItem(position).getEnd_time();
                if (null == message) {
                    message = new Message();
                } else {
                    message = Message.obtain();
                }
                message.what = 1;
                //发送信息给handler
                handler.sendMessage(message);
                adapter.notifyDataSetChanged();
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.voucher_detail:
                        isInit = false;
                        LayoutInflater inflater = (LayoutInflater) mcontext
                                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        View v = inflater.inflate(R.layout.dialog_voucher_detail, null);
                        TextView sure = (TextView) v.findViewById(R.id.dialog_sure);
                        TextView content = (TextView) v.findViewById(R.id.dialog_content);
                        ImageView voucher_iv = (ImageView) v.findViewById(R.id.voucher_iv);
                        TextView voucher_title = (TextView) v.findViewById(R.id.voucher_title);
                        TextView voucher_summary = (TextView) v.findViewById(R.id.voucher_summary);
                        LinearLayout usetime_ll = (LinearLayout) v.findViewById(R.id.usetime_ll);
                        TextView start_time = (TextView) v.findViewById(R.id.start_time);
                        TextView end_time = (TextView) v.findViewById(R.id.end_time);
                        LinearLayout foreveruse_ll = (LinearLayout) v.findViewById(R.id.foreveruse_ll);
                        TextView auction_bean = (TextView) v.findViewById(R.id.auction_bean);
                        TextView voucher_money = (TextView) v.findViewById(R.id.voucher_money);
                          content.setText(Html.fromHtml(adapter.getData().get(position).getContent()));
                        ObjectUtils.photo2(mcontext,adapter.getData().get(position).getThumb(),voucher_iv);
                        voucher_title.setText(adapter.getData().get(position).getTitle());
                        voucher_money.setText("售价: ¥"+adapter.getData().get(position).getPrice());
                        auction_bean.setText(adapter.getData().get(position).getCoin());
                        voucher_summary.setText(adapter.getData().get(position).getSummary());

                        if(adapter.getData().get(position).getEnd_time().equals("0"))
                        {
                            foreveruse_ll.setVisibility(View.VISIBLE);
                            usetime_ll.setVisibility(View.INVISIBLE);
                        }
                        else {
                            foreveruse_ll.setVisibility(View.INVISIBLE);
                            usetime_ll.setVisibility(View.VISIBLE);
                            int s_time = Integer.parseInt(adapter.getData().get(position).getStart_time());
                            long msl = (long) s_time * 1000;
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                            String text = format.format(msl);
                            start_time.setText(text);
                            // mainlistdata.setStart_time(text);
                            int e_time = Integer.parseInt(adapter.getData().get(position).getEnd_time());
                            long msl1 = (long) e_time * 1000;
                            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                            String text1 = format1.format(msl1);
                            end_time.setText(text1);
                        }
                        //  mainlistdata.setEnd_time(text1);

                        sure.setOnClickListener(new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View view) {
                                                        dialog.dismiss();
                                                    }
                                                }
                        );
                        dialog = new AlertDialog.Builder(mcontext).setView(v).setCancelable(true).show();
                        Window dialogWindow = dialog.getWindow();
                        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                        dialogWindow.setGravity(Gravity.BOTTOM);
                        dialogWindow.setAttributes(lp);
                    break;
                }
                return false;
            }
        });
        mRefreshLayout.setColorSchemeResources(R.color.app_title);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                if (networkConnected) {
                    page = 1;

                    GetDataListData(page);
                } else {
                    ObjectUtils.toast(mcontext, "网络连接出现异常");
                    mRefreshLayout.setRefreshing(false);
                }
            }
        });
    }




    @OnClick({R.id.main_top_back,R.id.click_resetnetwork_refresh,R.id.mine_voucher,R.id.add,R.id.reduce,R.id.gotopay})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_top_back:
                finish();
                break;
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                GetDataListData(page);
                break;
            case R.id.mine_voucher:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    Intent intent = new Intent(mcontext, MainTab.class);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, 0);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE, 9);
                    startActivity(intent);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
            case R.id.add:
                if(currentid!=null) {
                    if(currentnumber>=0) {
                        BigDecimal b1 = new BigDecimal(Double.toString(currentprice));
                        BigDecimal b2 = new BigDecimal(Double.toString(singleprice));
                        currentprice = b1.add(b2).doubleValue();
                        currentcoin = currentcoin + singlecoin;
                        currentnumber++;
                        really_price.setText(currentprice + "");
                        really_bean.setText(currentcoin + "");
                        buy_number.setText(currentnumber + "");
                    }
                }
                else
                {
                    ObjectUtils.toast(mcontext, "请选择商家券");
                }
                break;
            case  R.id.reduce:
                if(currentid!=null) {
                    if(currentnumber>0) {
                        BigDecimal b11 = new BigDecimal(Double.toString(currentprice));
                        BigDecimal b22 = new BigDecimal(Double.toString(singleprice));
                        currentprice = b11.subtract(b22).doubleValue();
                        currentcoin = currentcoin - singlecoin;
                        currentnumber--;
                        really_price.setText(currentprice + "");
                        really_bean.setText(currentcoin + "");
                        buy_number.setText(currentnumber + "");
                    }
                }
                else
                {
                    ObjectUtils.toast(mcontext, "请选择商家券");
                }
                break;
            case R.id.gotopay:
                if(currentid!=null) {
                    if(currentnumber>0) {
                        Intent intent = new Intent(mcontext, BaseObject.class);
                        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "购劵支付");
                        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, currentid);
                        intent.putExtra("singleprice", singleprice + "");
                        intent.putExtra("currentprice", currentprice + "");
                        intent.putExtra("currentnumber", currentnumber + "");
                        intent.putExtra("currentcoin", currentcoin + "");
                        intent.putExtra("currenttitle", currenttitle + "");
                        intent.putExtra("currentsummary", currentsummary + "");
                        intent.putExtra("currentthumb", currentthumb + "");
                        intent.putExtra("currentstime", currentstime + "");
                        intent.putExtra("currentetime", currentetime + "");
                        startActivity(intent);
                    }
                    else
                    {
                        ObjectUtils.toast(mcontext, "请选择商家券");
                    }
                }
                else
                {
                    ObjectUtils.toast(mcontext, "请选择商家券");
                }
                break;
        }
    }
    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetDataListData(page);
    }
    /**
     * 商品列表
     */
    private void GetDataListData(final int page) {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.VOUCHERLIST ;
        HashMap<String,String> map = new HashMap<>();
        map.put( "page", page+"");
        map.put("size","10");
        if (networkConnected) {

            HttpUtils.get(address, map, new BusinessVoucherListDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(BusinessVoucherListData response, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        listdata = new ArrayList<>();
                        BusinessVoucherListData.DataBean data = response.getData();
                        if(data !=null && data.getList()!=null && data.getList().size()>0)
                        {
                            mRecyclerView.setLayoutManager(mLayoutManager);
                            listdata.addAll(data.getList());
                            for(int i=0;i<listdata.size();i++)
                            {
                                listdata.get(i).setItemType(BusinessVoucherListData.DataBean.ListBean.THREE);
                            }
                            if (page == 1) {
                                adapter.setNewData(listdata);
                                mRecyclerView.setAdapter(adapter);

                            } else {
                                adapter.addData(listdata);
                                adapter.loadMoreComplete();
                            }
                            if(data.getList().size()<10)
                            {
                                adapter.loadMoreEnd();
                            }
                        }
                        else {
                            adapter.loadMoreEnd();
                        }
                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                    }
                }
            });
        } else {

            ObjectUtils.toast(mcontext, "网络未连接");
            adapter.loadMoreFail();
        }
    }
    public class AdaptList extends BaseMultiItemQuickAdapter<BusinessVoucherListData.DataBean.ListBean,BaseViewHolder > {
        private String type;
        private FragmentActivity mcontext;
        private int position;
        private String title;
        public List<BusinessVoucherListData.DataBean.ListBean> data;

        public AdaptList(FragmentActivity context, List<BusinessVoucherListData.DataBean.ListBean> data, String type) {
            super(data);
            this.data = data;
            this.mcontext = context;
            this.type = type;
            addItemType(BusinessVoucherListData.DataBean.ListBean.THREE, R.layout.item_buyticket);
        }

        @Override
        protected void convert(BaseViewHolder holder, BusinessVoucherListData.DataBean.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case BusinessVoucherListData.DataBean.ListBean.THREE:
                    if(isInit)
                    {
                        holder.getView(R.id.item_buyticket_ll).setBackgroundResource(R.drawable.corner_whiteborder_bg);
                    }
                    else {
                        if (currentid.equals(mainlistdata.getId())) {
                            holder.getView(R.id.item_buyticket_ll).setBackgroundResource(R.drawable.corner_redborder_bg);
                        } else {
                            holder.getView(R.id.item_buyticket_ll).setBackgroundResource(R.drawable.corner_whiteborder_bg);
                        }
                    }
                    holder.setText(R.id.voucher_price, mainlistdata.getPrice());
                    holder.setText(R.id.voucher_title, mainlistdata.getTitle());
                    holder.setText(R.id.voucher_summary, mainlistdata.getSummary());
                    if(mainlistdata.getEnd_time().equals("0"))
                    {
                        holder.setVisible(R.id.foreveruse_ll,true);
                        holder.setVisible(R.id.usetime_ll,false);
                    }
                    else {
                        holder.setVisible(R.id.foreveruse_ll, false);
                        holder.setVisible(R.id.usetime_ll, true);
                        int s_time = Integer.parseInt(mainlistdata.getStart_time());
                        long msl = (long) s_time * 1000;
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        String text = format.format(msl);
                        holder.setText(R.id.start_time, text);
                        // mainlistdata.setStart_time(text);
                        int e_time = Integer.parseInt(mainlistdata.getEnd_time());
                        long msl1 = (long) e_time * 1000;
                        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                        String text1 = format1.format(msl1);
                        holder.setText(R.id.end_time, text1);
                    }
                  //  mainlistdata.setEnd_time(text1);
                    holder.setText(R.id.auction_bean, mainlistdata.getCoin());
                    holder.addOnClickListener(R.id.voucher_detail);
                    break;

            }
        }
    }
}
